package com.zly.framework.rbac.handler.failed;

import com.alibaba.fastjson2.JSON;
import com.zly.framework.rbac.model.vo.Result;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@Schema(name = "登陆失败")
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        if (exception instanceof UsernameNotFoundException) {
            response.getWriter().write(JSON.toJSONString(Result.ERROR("用户名错误")));
        } else {
            if (exception instanceof BadCredentialsException) {
                response.getWriter().write(JSON.toJSONString(Result.ERROR("密码错误")));
            } else {
                response.getWriter().write(JSON.toJSONString(Result.ERROR("登陆失败")));
            }
        }

    }
}
